
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";

export default async function (ctx: FunctionContext) {
  let body = ctx.body
  if (nw.util.isNull(body.couponId)){
    return fail("参数不合法")
  }

  let coupon = await nw.db.findById({
    dbName:"couponInfo",
    id:body.couponId
  })
  if (nw.util.isNull(coupon)){
    return fail("优惠券不存在")
  }

  //2.构建更新数据
  let updateData = {
    rangeType:body.rangeType||coupon.rangeType,
    amount:body.amount||coupon.amount,
    conditionAmount:body.conditionAmount||coupon.conditionAmount,
    rangeDesc:body.rangeDesc||coupon.rangeDesc
  }

  await nw.db.update({
    dbName:"couponInfo",
    whereJson:{_id:coupon._id},
    dataJson:updateData
  })
  //3.构建优惠券规则列表
  let couponRangeList = body.couponRangeList
  if (!nw.util.isNull(couponRangeList)&&nw.util.isArray(couponRangeList)||couponRangeList.length>0){
    for (let i = 0; i < couponRangeList.length; i++) {
      couponRangeList[i].couponId = coupon._id
      couponRangeList[i].createTime = new Date()
      couponRangeList[i].updateTime = new Date()
      couponRangeList[i].deleted = 0
    }
    //删除原有的数据
    await nw.db.del({
      dbName:"couponRange",
      whereJson:{couponId:coupon._id}
    })

    await cloud.database().collection("couponRange").add(couponRangeList,{multi:true})
  }

  return ok("保存成功")
}
